package com.junxonline.instant.api.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.junxonline.instant.common.entity.common.CommonResult;
import com.junxonline.instant.common.enumeration.ApiErrorEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 认证拦截器
 *
 * @author JunX
 * @date 2021-09-03
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // TODO 统一拦截认证
        String terminalCode = request.getHeader("terminalCode");
        String token = request.getHeader("token");
        String sign = request.getHeader("sign");



        if (StrUtil.isNotBlank(terminalCode) && StrUtil.isNotBlank(token) && StrUtil.isNotBlank(sign)) {
            return true;
        }

        responseUnauthorized(response);
        return false;
    }

    /**
     * 认证失败响应
     *
     * @param response response
     */
    private void responseUnauthorized(ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.HTTP_OK);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        OutputStream out = null;
        try {
            out = httpServletResponse.getOutputStream();
            CommonResult result = CommonResult.fail(ApiErrorEnum.AUTH_FAIL.getCode(), ApiErrorEnum.AUTH_FAIL.getMsg());
            String resultJson = JSON.toJSONString(result);
            out.write(resultJson.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
